<template>
    <div :class='$style.container'>
        <aside :class='$style.aside'>
            <div class='p-l'>
                <StockSelector @finish='finishSelectStock' />
            </div>
            <div class='m-t-10'>
                <a-tree checkable v-model:checkedKeys='checkedKeysOfIndustryRows' :height='treeHeight' :fieldNames='{children : "children", title : "label", key : "id"}' :tree-data='industryOptions' @check='industryOnCheck'></a-tree>
            </div>
            <div class='m-t-10'>
                <a-tree checkable v-model:checkedKeys='checkedKeysOfFactorRows' :height='treeHeight' :fieldNames='{children : "children", title : "label", key : "label_id"}' :tree-data='factorOptions' @check='factorOnCheck'></a-tree>
            </div>
        </aside>
        <div class='flex-1 overflow'>
            <div style="width:100%;overflow-x:auto">
                <template v-if='!loading'>
                    <div class='flex-align-items-center'>
                        <span class='flex-1'>
                            <a-button type='primary' @click='openSetParams'>设置参数</a-button>
                            <a-button class='m-l-10' type='primary' @click='clearIndustry'>清空证券列表</a-button>
                            <a-button class='m-l-10' type='primary' @click='toggleChart'>{{showChart ? '关闭图形' : '显示图形'}}</a-button>
                        </span>
                        <span class='m-l-20 p-r'>
                            共 <span class='color-forbidden bold'>{{dataSource.length}}</span> 只选股结果
                        </span>
                    </div>
                    <div class='m-t-20'>
                        <div v-if='showChart'>
                            <Chart :params='chartData' />
                        </div>
                        <ElTable :header-row-class-name='$style.th' row-key='code' :data="dataSource" style="width: 100%" max-height="800">
                            <template #empty>
                                <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" />
                            </template>
                            <template v-for='column in columns' :key='column.dataIndex'>
                                <ElTableColumn align='center' :prop='column.dataIndex' :label='column.title' />
                            </template>
                        </ElTable>
                        <!-- <a-table rowKey='code' :class='$style.resultTable' align='center' :scroll="{ y: '500px'}" :pagination='false' :dataSource='dataSource' :columns='columns'></a-table> -->
                    </div>
                </template>
                <template v-else>
                    <a-skeleton active />
                </template>
            </div>
        </div>
    </div>

    <a-modal v-model:visible='visible' title='设置参数' :confirm-loading='loading' @ok='paramsConfirm'>
        <div :class='$style.paramRow' v-for='(row, index) in selectedFactorRows' :key='row.label_id'>
            <div :class='$style.name'>
                <a-tooltip>
                    <template #title>{{row.label}}</template>
                    <div :class='$style.content'>{{row.label}}</div>
                </a-tooltip>
            </div>
            <div :class='$style.ctr'>
                <template v-for='(param, i) in row.params' :key='i'>
                    <div>
                        <div class='f-12'>{{param.name}}</div>
                        <template v-if='param.type == 1'>
                            <a-input class='w-100' v-model:value='param.v' />
                        </template>
                        <template v-else>
                            <a-select class='w-100' v-model:value='param.v' :options='param.options'></a-select>
                        </template>
                    </div>
                </template>
            </div>
        </div>
    </a-modal>

</template>

<script lang='ts' setup>
import { ElTable, ElTableColumn, ElScrollbar } from 'element-plus'
import 'element-plus/es/components/table/style/css'
import 'element-plus/es/components/scrollbar/style/css'
    import { industryTreeApi, industrySelectStockApi } from '@/api/industry'
    import { queryByFactorApi } from '@/api/stockBoard'
    import { stockFinancialFactorApi } from '@/api/stockSelector'
    import { computed, reactive, ref } from '@vue/reactivity'
    import { onMounted } from '@vue/runtime-core'
    import { message } from 'ant-design-vue'
    import StockSelector from './StockSelector.vue'
    import Chart from './Chart.vue'
    import { Empty } from 'ant-design-vue';

    const visible = ref(false)

    const industryOptions = ref([{
        id : '0',
        label : '行业分类',
        checkable : false,
        children : []
    }])

    const factorOptions = ref([
        {
            label_id : '0',
            label : '财务因子',
            checkable : false,
            children : []
        }
    ])
    
    const checkedKeysOfIndustryRows = ref<number[]>([])
    const checkedKeysOfFactorRows = ref<number[]>([])

    const industryRows = reactive<any[]>([])
    const factorRows = reactive<any[]>([])

    const selectedFactorSet = new Set()

    const showChart = ref(false)
    const loading = ref(false)
    const columns = ref<any[]>([{title : '证券代码', dataIndex : 'code'}, {title : '股票名称', dataIndex : 'name'}])
    const dataSource = reactive<any[]>([])
    const codes = reactive<any[]>([]) //从选股器选中的code
    const selectedFactorRows = reactive<any[]>([]) //参数设置列表


    // for(let i = 0; i < 2; i ++) {
    //     columns.value.push({title : '士大夫撒发射点发生' + i, dataIndex : 's' + i})
    //     dataSource.push({code : '34gresf', name : '日前，国务院常务会议听取了河南郑州“7·20”特大暴雨灾害调查情况的汇报，并审议通过了河南郑州“7·20”特大暴雨灾害调查报告。经国务院调查组调查认定，河南郑州“7·20”特大暴雨灾害是一场因极端暴雨导致严重城市内涝、河流洪水、山洪滑坡等多灾并发，造成重大人员伤亡和财产损失的特别重大自然灾害；郑州市委市政府及有关区县（市）、部门和单位风险意识不强，对这场特大灾害认识准备不足、防范组织不力、应急处置不当，存在失职渎职行为，特别是发生了地铁、隧道等本不应该发生的伤亡事件。', ['s' + i] : '232234324324'})
    // }


    const factorFields = reactive<any[]>([])
    const chartData = reactive({
        name : [],
        data : [],
        fields : []
    })

    function openSetParams() {
        visible.value = true
    }

    function toggleChart(){
        showChart.value = !showChart.value
    }

    function clearIndustry() {
        columns.value.splice(2)
        dataSource.splice(0)

        checkedKeysOfIndustryRows.value.splice(0)
        checkedKeysOfFactorRows.value.splice(0)

        showChart.value = false
    }

    async function industryOnCheck(ids:number[]) {
        //columns.value.splice(2)

        dataSource.splice(0)
        if(ids.length > 0) {
            loading.value = true
            const res = await industrySelectStockApi(ids)
            loading.value = false
            if(res.success) {
                res.data.forEach(row => {
                    if(!codes.includes(row.code)) {
                        codes.push(row.code)
                        dataSource.push(row)
                    }
                })
                
            }else {
                message.error(res.message)
            }
        }
        
    }

    async function factorOnCheck(ids:number[], {checkedNodes}) {
        if(checkedKeysOfFactorRows.value.length > 50) {
            checkedKeysOfFactorRows.value.splice(selectedFactorRows.length)
            message.error('最多只能选择50个财务因子')
            return
        }
        
        
        columns.value.splice(2)

        let rows = JSON.parse(JSON.stringify(checkedNodes.filter(node => node.params)))


        if(rows.length > 0) {
            rows.forEach(row => {
                columns.value.push({title : row.label, dataIndex : row.label})
            })
            if(rows.length > selectedFactorRows.length) { //新增
                for(let i = selectedFactorRows.length; i < rows.length; i ++) {
                    const row = rows[i]

                    row.params.forEach(item => {
                        item.v = ''
                        item.options = []
                        if(item.value && item.value.length > 0) {
                            const value = JSON.parse(JSON.stringify(item.value))
                            delete item.value

                            if(typeof value[0] == 'object') {
                                let key = (Object.keys(value[0]))[0]
                                value.forEach(v => {
                                    item.options.push({
                                        label : key,
                                        value : v[key]
                                    })
                                })
                            }else {
                                item.v = value[0]
                                value.forEach(v => {
                                    item.options.push({label : v, value : v})
                                })
                            }

                        }

                    })

                    selectedFactorRows.push(row)
                }

                visible.value = true
            }else {
                let keys = rows.map(row => row.label_id)
                let selectedKeys = selectedFactorRows.map(row => row.label_id)
                let _tmp = selectedFactorRows.splice(0)
                selectedKeys.forEach((key, index) => {
                    if(keys.includes(key)) {
                        selectedFactorRows.push(_tmp[index])
                    }
                })
            }

            
            //factorSelectStock()
        }else {
            selectedFactorRows.splice(0)
        }
    }

    async function factorSelectStock() {
        if(codes.length == 0) {
            message.error('请选择股票')
            return
        }
        let params = {
            codes : codes.join(','),
            factor : []
        }

        console.log(selectedFactorRows.length == 0)

        factorFields.splice(0)
        chartData.name.splice(0)
        chartData.data.splice(0)
        chartData.fields.splice(0)

        selectedFactorRows.forEach(row => {
            chartData.fields.push(row.label)
            factorFields.push({title : row.label, dataIndex : row.label})

            const factor = {
                factor_name : row.en_name,
                factor_params : []
            }
            row.params.forEach(param => {
                factor.factor_params.push({
                    code : param.code,
                    value : param.v
                })
            })

            params.factor.push(factor)
        })

        dataSource.splice(0)

        loading.value = true
        const res = await queryByFactorApi(params)
        loading.value = false
        if(res.success) {
            res.data.forEach(row => {
                dataSource.push(row)

                chartData.name.push(row.name)
                
                let rows = []
                chartData.fields.forEach(field => {
                    rows.push(row[field])
                })

                chartData.data.push(rows)
            })

            console.log(chartData)

        }else {
            message.error(res.message)
        }
    }

    async function paramsConfirm() {
        await factorSelectStock()
        visible.value = false
    }

    async function finishSelectStock(rows) { //从选股器完成选择股票
        rows.forEach(row => {
            if(!codes.includes(row.code)) {
                codes.push(row.code)
                dataSource.push(row)
            }
        })
    }
    

    industryTreeApi().then(rows => {
        function reduce(rows, level=0) {
            rows.forEach(row => {
                row.checkable = level != 0
                if(row.children && row.children.length > 0){
                    reduce(row.children, level + 1)
                }
            })
        }

        if(rows) {
            reduce(rows)
            industryOptions.value[0].children = rows
        }
    })

    stockFinancialFactorApi().then(rows => {
        function reduce(data, level=0) {
            data.forEach(row => {
                row.checkable = level != 0
                if(row.children) {
                    reduce(row.children, 1)
                }
            })
        }

        if(rows) {
            reduce(rows, 0)
            factorOptions.value[0].children = rows
        }
        
    })

</script>


<style lang='scss' module>
    $sideW : 300px;
    $sideLeft : 10px;
    .container{
        height: 100%;
        position: relative;
        display: flex;
        .aside{
            background: #fff;
            max-width: $sideW;
            min-width: 150px;
            margin-right: 20px;
            //border: 1px solid $border-color;
        }
    }

    .resultTable{
        :global(.ant-table-cell){
            text-align: center;
        }
    }

    .paramRow{
        display: flex;
        align-items: center;
        padding: 0px 10px;
        margin-top: 5px;
        &:first-child{
            margin-top: 0;
        }

        .name{
            width: 120px;
            .content{
                white-space:nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                font-size: 12px;
            }
        }

        .ctr{
            flex: 1;
            
        }
    }

    .th{
        color: #333;
        padding: 10px 0 !important;
        //text-align: center;
    }
</style>